package com.leo.erp.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.erp.dao.AccountHeadMapper;
import com.leo.erp.dao.DepotHeadMapper;
import com.leo.erp.dao.PersonMapper;
import com.leo.erp.dto.PersonExecution;
import com.leo.erp.entity.AccountHead;
import com.leo.erp.entity.DepotHead;
import com.leo.erp.entity.Person;
import com.leo.erp.entity.User;
import com.leo.erp.enums.PersonStateEnum;
import com.leo.erp.service.LogService;
import com.leo.erp.service.PersonService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.StringUtil;

@Service
public class PersonServiceImpl implements PersonService{
	@Autowired
	private PersonMapper personMapper;
	@Autowired
	private AccountHeadMapper accountHeadMapper;
	@Autowired
	private DepotHeadMapper depotHeadMapper;
	@Autowired
	private LogService logService;

	@Override
	public PersonExecution getPersonByType(String type) {
		PersonExecution pe = new PersonExecution();
		QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("type", type);
		queryWrapper.ne("deleteFlag", "1");
		queryWrapper.orderByAsc("personId");
		
		try {
			List<Person> list = personMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				pe.setState(PersonStateEnum.SUCCESS.getState());
				pe.setPersonList(list);
			}else {
				pe.setState(PersonStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return pe;
	}

	/**
	 * 正常删除，要考虑数据完整性，进行完整性校验
	 */
	@Override
	@Transactional
	public PersonExecution batchDeletePersonByIdsNormal(String ids) {
		PersonExecution pe = new PersonExecution();
		/**
         * 校验
         * 1、财务主表	tb_account_head
         * 2、单据主表	tb_depot_head
         * 是否有相关数据
         * */
		if(StringUtil.isEmpty(ids)) {
			pe.setState(PersonStateEnum.OFFLINE.getState());
			return pe;
		}
		List<Long> idList = StringUtil.strToLongList(ids);//转换成数组
		/**
         * 校验财务主表	tb_account_head
         * */
		try {
			QueryWrapper<AccountHead> queryAccountHead = new QueryWrapper<>();
			queryAccountHead.in("handsPersonId", idList);
			List<AccountHead> accountHeadList = accountHeadMapper.selectList(queryAccountHead);
			if(accountHeadList.size() > 0) {
				//有数据,可以执行强制删除
				pe.setState(PersonStateEnum.DELETE.getState());
				return pe;
				//throw new GlobalRuntimeException("检测到存在依赖数据，是否强制删除？");
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		/**
		 * 检验单据主表tb_depot_head
		 */
		try {
			QueryWrapper<DepotHead> queryDepotHead = new QueryWrapper<>();
			queryDepotHead.in("handsPersonId", idList);
			List<DepotHead> depotHeadList = depotHeadMapper.selectList(queryDepotHead);
			if(depotHeadList.size() > 0) {
				pe.setState(PersonStateEnum.DELETE.getState());
				return pe;
				//throw new GlobalRuntimeException("检测到存在依赖数据，是否强制删除？");
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		/**
		 * 校验通过执行删除操作
		 */
		int effectedNum = batchDeleteSupplierByIds(ids);
		if(effectedNum > 0) {
			pe.setState(PersonStateEnum.SUCCESS.getState());
		}else {
			pe.setState(PersonStateEnum.OFFLINE.getState());
		}
		
		return pe;
	}
	
	@Transactional
	@Override
	public int batchDeleteSupplierByIds(String ids) {
		StringBuffer sb = new StringBuffer();
		List<Long> idList = StringUtil.strToLongList(ids);
		QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("personId", idList);
		List<Person> list = personMapper.selectList(queryWrapper);
		for(Person person : list) {
			sb.append("[").append(person.getName()).append("]");
		}
		logService.insertLog("经手人", sb.toString(), ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
		//session
		HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		User user = (User) request.getSession().getAttribute("user");
		int effectedNum = 0;
		try {
			Person person = new Person();
			person.setDeleteFlag("1");
			person.setTenantId(user.getUserId());
			UpdateWrapper<Person> updateWrapper = new UpdateWrapper<>();
			updateWrapper.in("personId", idList);
			
			effectedNum = personMapper.update(person, updateWrapper);
			
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return effectedNum;
	}

	@Override
	@Transactional
	public PersonExecution insertPerson(String beanJson, HttpServletRequest request) throws GlobalRuntimeException{
		PersonExecution pe = new PersonExecution();
		Person person = JSONObject.parseObject(beanJson, Person.class);
		//session
		User user = (User) request.getSession().getAttribute("user");
		person.setTenantId(user.getUserId());
		
		try {
			int effectedNum = personMapper.insert(person);
			if(effectedNum > 0) {
				logService.insertLog("经手人", "新增:" + person.getName().toString(), request);
				pe.setState(PersonStateEnum.SUCCESS.getState());
			}else {
				pe.setState(PersonStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return pe;
	}

	@Override
	public PersonExecution updatePerson(String beanJson, int personId, HttpServletRequest request) {
		PersonExecution pe = new PersonExecution();
		Person person = JSONObject.parseObject(beanJson, Person.class);
		person.setPersonId(personId);
		//session
		User user = (User) request.getSession().getAttribute("user");
		person.setTenantId(user.getUserId());
		try {
			int effectedNum = personMapper.updateById(person);
			if(effectedNum > 0) {
				logService.insertLog("经手人", "修改:" + person.getName().toString(), request);
				pe.setState(PersonStateEnum.SUCCESS.getState());
			}else {
				pe.setState(PersonStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return pe;
	}

	@Override
	public PersonExecution getList(String name, String type, int currentPage, int pageSize) {
		PersonExecution pe = new PersonExecution();
		QueryWrapper<Person> queryWrapper = new QueryWrapper<>();
		//判断
		if(name != null && name != "") {
			queryWrapper.like("name", name);
		}
		if(type != null && type != "") {
			queryWrapper.like("type", type);
		}
		queryWrapper.ne("deleteFlag", "1");
		
		Page<Person> page = new Page<>(currentPage, pageSize);//分页查询
		IPage<Map<String, Object>> iPage = personMapper.selectMapsPage(page, queryWrapper);
		if(iPage.getRecords().size() > 0) {
			pe.setState(PersonStateEnum.SUCCESS.getState());
			pe.setPages(page.getPages());//总页数
			pe.setTotal(iPage.getTotal());//总记录数
			pe.setPersonPageList(iPage.getRecords());
		}else{
			pe.setState(PersonStateEnum.OFFLINE.getState());
		}
		
		return pe;
	}
	
	
}
